<?php
/**
 * Created by xiaosong
 * E-mail:4155433@gmail.com
 * Date: 2019/4/10
 * Time: 16:04
 */

namespace app\api\controller;


use app\common\logic\MyPackage;
use app\common\model\DrawCustom;
use app\common\model\DrawRecord;
use app\common\service\AppService;
use app\common\service\DrawService;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;

class Draw extends User
{

    public function _initialize()
    {
        parent::_initialize();



        $this->assign([
            'version' => 3.30
        ]);
    }


    /**
     * 检查活动是否开启
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    protected function checkAct()
    {
        if (self::getExplain('activity') !== 'open' ){
            if (input('test') !== 'xiaosong'){
                api_return(0,'活动维护中,请稍后重试');
            }
        }
    }

    /**
     *
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function index()
    {
        $model = new DrawRecord();

        $day  = $model->dayRanking();
        $week = $model->weekRanking();
        $selfDay  = $model->dayRanking(['u.user_id'=>$this->user_id])[0];
        $selfWeek = $model->weekRanking(['u.user_id'=>$this->user_id])[0];
        $hash = hashid($this->user_id);

        foreach ($day as $k => $v){
            if ($v['user_id'] === $hash){
                $selfDay['rank'] = $k +1;
                break;
            }
        }

        foreach ($week as $k => $v){
            if ($v['user_id'] === $hash){
                $selfWeek['rank'] = $k +1;
                break;
            }
        }

        $map['status'] = 1;
        $map['type']   = 1;
        $map['chance'] = ['neq',0];
        $prize = Db::name('draw')->where($map)->order('price')->field('name,price,type,key')->cache(60)->select();

        foreach ($prize as $k => $v){

            if ($v['type'] == 1){ //礼物
                $map1['gift_id'] = $v['key'];
                $map1['status']  = 1;
                $gift = Db::name('gift')->where($map1)->cache(3)->find();
                if ($gift){
                    $prize[$k]['name'] = $gift['gift_name'];
                    $prize[$k]['price'] = $gift['price'];
                    $prize[$k]['img'] = $gift['thumbnail'];
                }else{
                    unset($prize[$k]);
                }
            }
        }

        $hammer = $this->userInfo('money,cash,hammer_num,hammer_give,nick_name,header_img');

        $hammer['total']       = bcadd($hammer['money'],$hammer['cash'],1);
        $hammer['totalHammer'] = bcadd($hammer['hammer_num'],$hammer['hammer_give'],0);

        $info = self::getExplain('limit,hammerPrice,givePrice,giveOpen');
        $this->assign([
            'prize' => $prize,
            'info' => $info,
            'hammer' => $hammer,
            'token' => $this->token,
            'day' => $day,
            'week' => $week,
            'selfDay' => $selfDay,
            'selfWeek' => $selfWeek,
        ]);
        return view();
    }

    /**
     * 购买锤子
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function hammer()
    {
        $this->checkAct();

        $this->ApiLimit(5,$this->user_id);
        $num = input('num');

        if (!isInt($num)){
            api_return(0,'数量错误');
        }

        $hammerPrice = self::getExplain('hammerPrice');

        $total = bcmul($num,$hammerPrice,2);

        Db::startTrans();
        try{
            $this->moneyDec($total);

            Db::name('users')->where('user_id',$this->user_id)->setInc('hammer_num',$num);

            money_detail(2,$this->user_id,'抽奖活动->购买'.$num.'把锤子',$total,'消费');

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }
        $balance = $this->userBalance();
        $this->destroyLimit($this->user_id);
        api_return(1,'购买成功',$balance);
    }

    /**
     * 砸蛋
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function smash1()
    {
        $this->ApiLimit(5,$this->user_id);

        $num = input('num');

        if (!isInt($num)){
            api_return(0,'数量错误');
        }

        $hammer = $this->userInfo('hammer_num,hammer_give');

        $hammer['total'] = bcadd($hammer['hammer_num'],$hammer['hammer_give'],0);

        if ($hammer['total'] < $num){
            api_return(0,'锤子数量不足,不能砸蛋');
        }

        $map['status'] = 1;
        $map['type']   = 1;
        $rows = Db::name('draw')->where($map)->select();
        $proArr  = [];
        //赠送锤子抽奖概率
        $proArr2 = [];

        $prize   = [];

        foreach ($rows as $value){
            $proArr[$value['id']]  = $value['chance'];
            $proArr2[$value['id']] = $value['giveChance'];
            $prize[$value['id']]   = $value;
        }

        $win = [];

        for ($i = 1;$i <= $num;$i++){
            if ($hammer['hammer_give'] > 0){
                $id = getRand($proArr2);
                $hammer['hammer_give'] --;
            }else{
                $id = getRand($proArr);
                $hammer['hammer_num'] --;
            }
            if (isset($win[$id])){
                $win[$id] ++;
            }else{
                $win[$id] = 1;
            }
        }

        $Prizes = [];
        //算出中了哪些奖品
        foreach ($win as $k => $v){
            if ($k == 11){ //k等于11即未中奖
                continue;
            }
            $item['key']    = $prize[$k]['key'];
//            $item['user_id'] = $this->user_id;
            $item['type']   = $prize[$k]['type'];
            $item['remark'] = $prize[$k]['remark'];
            $item['num']    = $v;

            if ($item['type'] == 1){
                $item['name']  = getGiftName($item['key']);
                $item['img']   = getGiftImg($item['key']);
                $item['price'] = getGiftPrice($item['key']);
            }else{
                $item['name']  = $prize[$k]['name'];
                $item['img']   = $prize[$k]['img'];
                $item['price'] = $prize[$k]['price'];
            }
            $Prizes[] = $item;
        }


        $model = new MyPackage();

        Db::startTrans();
        try{

            //更新锤子
            Db::name('users')->strict(false)->where('user_id',$this->user_id)->update($hammer);

            //更新背包及中奖记录
            foreach ($Prizes as $k => $v){
                $map = [];
                $map['user_id'] = $this->user_id;
                $map['type']    = $v['type'];
                $map['key']     = $v['key'];
                $has = $model->where($map)->find();
                if ($has){
                    $model->where('p_id',$has['p_id'])->setInc('num',$v['num']);
                }else{
                    $map['num'] = $v['num'];
                    $model->insert($map);
                }

                $map['num']   = $v['num'];
                $map['total'] = $v['price'] * $v['num'];
                $map['price'] = $v['price'];

                $map['create_time'] = time();
                $map['update_time'] = time();
                $map['remark']      = '砸金蛋';

                $data = $v;

                $data['nick_name'] = self::staticInfo('nick_name',$this->user_id);
                $data['user_id']   = hashid($this->user_id);
                $data['remark']    = $map['remark'];

                if (is_numeric(input('room_id'))){
                    $this->sendRoomMsg(input('room_id'),'activity',$data);

                    //砸中大礼物进行推送
                    if ($v['price'] >= self::getExplain('mini_price')){
                        $roomInfo = $this->roomInfo(input('room_id'),'room_name,img,type,room_id,is_lock,password,cid');
                        $title = sprintf('恭喜【%s】刚刚在%s中获得【%s钻】x%s，又一波奖品已来袭~快来试试手气吧',$data['nick_name'],$map['remark'],$v['name'].'/'.$v['price'],$v['num']);
                        j_push($title,'all',$roomInfo);
                    }

                }

                Db::name('draw_record')->insert($map);
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }
        $this->destroyLimit($this->user_id);
        $new = arr_sort($Prizes,'price');

        api_return(1,'抽奖完成',$new);

    }


    public function smash()
    {
        $this->checkAct();
        $this->ApiLimit(5,$this->user_id);

        $num = input('num');

        if (!isInt($num)){
            api_return(0,'数量错误');
        }

        $max = self::getExplain('openMax')??100;
        if ($num > $max){
            api_return(0,sprintf("宝箱每次最多只能开%s个哦~",$max));
        }

        $hammer = Db::name('users')->where('user_id',$this->user_id)->field('hammer_num,hammer_give')->find();

        $hammer['total'] = bcadd($hammer['hammer_num'],$hammer['hammer_give'],0);

        if ($hammer['total'] < $num){
            api_return(0,'锤子数量不足,不能砸蛋');
        }

        $map['status'] = 1;
        $map['type']   = 1;
        $rows = Db::name(DrawService::$table)->where($map)->cache(15)->select();

//        $proArr  = [];
        //赠送锤子抽奖概率
//        $proArr2 = [];

        $prize   = [];

        foreach ($rows as $value){
//            $proArr[$value['id']]  = $value['chance'];
//            $proArr2[$value['id']] = $value['giveChance'];
            $prize[$value['id']]   = $value;
        }

        //查询是否有为中奖的指定中奖数据
        $custom['user_id'] = $this->user_id;
        $custom['status']  = 1;
        $custom['type']    = 1;
        $drawCustom = DrawCustom::where($custom)->find();

        $win = [];
        for ($i = 1;$i <= $num;$i++){
            if ($hammer['hammer_give'] > 0){
                $id = DrawService::draw1('giveChance');
                $hammer['hammer_give'] --;
            }else{
                $id = DrawService::draw1('chance');
                $hammer['hammer_num'] --;
            }

            
            if ($drawCustom){

                $num1 = $num - $drawCustom['num'];
                if ($i > $num1){
                    if (!isset($win[$drawCustom['draw_id']]) || $win[$drawCustom['draw_id']] < $drawCustom['num']){
                        $id = $drawCustom['draw_id'];
                    }
//                    $id = $drawCustom['draw_id'];
                }


                $drawCustom->save(['status'=>2]);
            }

            if (isset($win[$id])){
                $win[$id] ++;
            }else{
                $win[$id] = 1;
            }

        }

        $Prizes = [];
        //算出中了哪些奖品
        foreach ($win as $k => $v){
            if ($k == 11){ //k等于11即未中奖
                continue;
            }

            $item['key']    = $prize[$k]['key'];
//            $item['user_id'] = $this->user_id;
            $item['type']   = $prize[$k]['type'];
            $item['remark'] = $prize[$k]['remark'];
            $item['num']    = $v;



            if ($item['type'] == 1){
                $item['name']  = getGiftName($item['key']);
                $item['img']   = getGiftImg($item['key']);
                $item['price'] = getGiftPrice($item['key']);
            }else{
                $item['name']  = $prize[$k]['name'];
                $item['img']   = $prize[$k]['img'];
                $item['price'] = $prize[$k]['price'];
            }
            $Prizes[] = $item;

        }

        $model = new MyPackage();

        Db::startTrans();
        try{
            $push = [];
            //更新锤子
            Db::name('users')->strict(false)->where('user_id',$this->user_id)->update($hammer);

//            $insert2 = [];
//            $insert  = [];
//            $update  = [];
            //更新背包及中奖记录
            foreach ($Prizes as $k => $v){
                $map = [];
                $map['user_id'] = $this->user_id;
                $map['type']    = $v['type'];
                $map['key']     = $v['key'];
                $has = $model->where($map)->find();
                if ($has){
                    $map['num'] = $has['num']+$v['num'];
//                    $update[] = $map;
                    $model->where('p_id',$has['p_id'])->setInc('num',$v['num']);
                }else{
                    $map['num'] = $v['num'];
//                    $insert[] = $map;

                    $model->insert($map);
                }

                $map['num']   = $v['num'];
                $map['total'] = $v['price'] * $v['num'];
                $map['price'] = $v['price'];

                $map['create_time'] = time();
                $map['update_time'] = time();
                $map['remark']      = '砸金蛋';

                $data = $v;

                $data['nick_name'] = self::staticInfo('nick_name',$this->user_id);
                $data['level'] =   AppService::getUserInfo('level',$this->user_id);
                $data['user_id']   = hashid($this->user_id);
                $data['remark']    = $map['remark'];

                $push[] = $data;
//                $insert2[] = $map;
                Db::name('draw_record')->insert($map);
            }

//            if (!empty($update)) $model->saveAll($update);
//            if (!empty($insert)) $model->insertAll($insert);
//            if (!empty($insert2)) DrawRecord::insertAll($insert2);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $cache = cache('smashLog');
            $error['msg'] = 'smashLogRecord';
            $error['request']['param']  = \request()->param();
            $error['request']['header'] = \request()->header();
            $error['e'] = $e;
            $cache[] = $error;
            cache('smashLog',$cache);
            Log::write(json_encode($error),'xiaosong');
            api_return(0,$e->getMessage());
        }

        foreach ($push as $k => $data){
            if (is_numeric(input('room_id'))){
                if ($data['price'] >= self::getExplain('activity_mini')){
                    $this->sendRoomMsg('all','activity',$data);
                }

                //砸中大礼物进行推送
                if ($data['price'] >= self::getExplain('mini_price')){
                    $roomInfo = $this->roomInfo(input('room_id'),'room_name,img,type,room_id,is_lock,password,cid');
                    $title = sprintf('恭喜【%s】刚刚在%s中获得【%s钻】x%s，又一波奖品已来袭~快来试试手气吧',$data['nick_name'],$map['remark'],$data['name'].'/'.$data['price'],$data['num']);
                    j_push($title,'all',$roomInfo);
                }

            }
        }

        $this->destroyLimit($this->user_id);
        $new = arr_sort($Prizes,'price');

        api_return(1,'抽奖完成',$new);

    }
    /**
     * 中奖记录
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function prise()
    {
        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        $limit = self::getExplain('limit');
        $rows  = Db::name('draw_record')->where($map)->order('record_id desc')->limit($limit)->field('user_id',true)->select();

        foreach ($rows as $k => $v){
            if ($v['type'] == 1){
                $rows[$k]['name'] = getGiftName($v['key']);
                $rows[$k]['img']  = getGiftImg($v['key']);
            }
        }

        api_return(1,'获取成功',$rows);

    }

    /**
     * 我的背包
     * @param Request $request
     */
    public function myPackage(Request $request)
    {
        $map['p.user_id'] = $this->user_id;
        $type = $request->param('type');

        if ($type){
            $map['p.type'] = $type;
            if ($type == 1){
                //不是礼物类型即使为0也要想显示
                $map['p.num'] = ['>',0];
            }
            $rows['rows']  = \app\common\model\MyPackage::getRows($map);
        }else{
            $map['p.type'] = ['neq',1];
            $card = \app\common\model\MyPackage::getRows($map);

            $map['p.type'] = 1;
            $map['p.num']  = ['>',0];

            $gift = \app\common\model\MyPackage::getRows($map);

            $rows['rows'] = array_merge($card,$gift);
        }

        $rows['balance'] = $this->userBalance();

        api_return(1,'获取成功',$rows);
    }

    /**
     * 赠送宝箱接口
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function giftBox($type)
    {

        if (self::getExplain('boxAct') === 'true'){
            api_return(0,'今日已获取过宝箱');
        }

        $this->ApiLimit(5,$this->user_id);
        switch ($type){
            case 4://铜宝箱
                break;
            case 5://银宝箱
                break;
            case 6://金宝箱
                break;
            default:
                api_return(0,'参数错误');
        }
        $cache = cache($type.'giftBox_'.$this->user_id);
        if ($cache){
            api_return(0,'今日已获取过宝箱');
        }

        $map['user_id'] = $this->user_id;
        $map['type']    = $type;

        $model = new MyPackage();

        $has = $model->where($map)->find();
        if ($has){
            $result = $has->setInc('num');
        }else{
            $map['num'] = 1;
            $result = $model->insert($map);
        }

        if ($result !== false){
            cache($type.'giftBox_'.$this->user_id,1,todayEndTime());
            api_return(1,'获取宝箱成功');
        }
        api_return(0,'系统繁忙,请稍后重试');

    }

    /**
     * 开宝箱
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
//    public function openBox1()
//    {
//        $data = input('post.');
//
//        switch ($data['type']){
//            case 4://铜宝箱
//                $name = '铜';
//                break;
//            case 5://银宝箱
//                $name = '银';
//                break;
//            case 6://金宝箱
//                $name = '金';
//                break;
//            default:
//                api_return(0,'参数错误');
//        }
//
//        $type = $data['type'];
//
//        if (!isInt($data['num'])){
//            api_return(0,'开启数量错误');
//        }
//
//        // 2019-7-23 修改开宝箱为无限次数
////        $map['user_id'] = $this->user_id;
////        $map['type']    = $data['type'];
////
//        $model = new MyPackage();
////
////        $row   = $model->where($map)->find();
////
////        if (!$row || $row['num'] < $data['num']){
////            api_return(0,'宝箱剩余数量不足');
////        }
//
//        $map2['status'] = 1;
//        $map2['type']   = 1;
//
//        $rows   = Db::name('draw')->where($map2)->cache(3)->select();
//        $proArr = [];
//        $prize  = [];
//
//        foreach ($rows as $value){
//            $proArr[$value['id']]  = $value['box'.$data['type']];
//
//            $prize[$value['id']]   = $value;
//        }
//
//
//        $win = [];
//
//        for ($i = 1;$i <= $data['num'];$i++){
//
//            $id = getRand($proArr);
//
//            if ($id){
//                if (isset($win[$id])){
//                    $win[$id] ++;
//                }else{
//                    $win[$id] = 1;
//                }
//            }
//
//        }
//
//        $Prizes = [];
//        //算出中了哪些奖品
//        foreach ($win as $k => $v){
//            if ($k == 11){ //k等于11即未中奖
//                continue;
//            }
//            $item['key']    = $prize[$k]['key'];
////            $item['user_id'] = $this->user_id;
//            $item['type']   = $prize[$k]['type'];
//            $item['remark'] = $prize[$k]['remark'];
//            $item['num']    = $v;
//
//            if ($item['type'] == 1){
//                $item['name']  = getGiftName($item['key']);
//                $item['img']   = getGiftImg($item['key']);
//                $item['price'] = getGiftPrice($item['key']);
//            }else{
//                $item['name']  = $prize[$k]['name'];
//                $item['img']   = $prize[$k]['img'];
//                $item['price'] = $prize[$k]['price'];
//            }
//            $Prizes[] = $item;
//        }
//        Db::startTrans();
//        try{
//            // 2019-7-23 修改开宝箱为无限次数
//            //更新宝箱
////            $row->setDec('num',$data['num']);
//            //扣钱
//            $price = self::getExplain('box'.$data['type']);
//            $total = bcmul($price,$data['num']);
//
//            $this->moneyDec($total,$this->user_id);
//            money_detail(2,$this->user_id,'抽奖活动->购买'.$data['num'].'把'.$name.'钥匙',$total);
//            //更新背包及中奖记录
//            foreach ($Prizes as $k => $v){
//                $map = [];
//                $map['user_id'] = $this->user_id;
//                $map['type']    = $v['type'];
//                $map['key']     = $v['key'];
//                $has = $model->where($map)->find();
//                if ($has){
//                    $model->where('p_id',$has['p_id'])->setInc('num',$v['num']);
//                }else{
//                    $map['num'] = $v['num'];
//                    $model->insert($map);
//                }
//
//                $map['num']   = $v['num'];
//                $map['total'] = $v['price'] * $v['num'];
//                $map['price'] = $v['price'];
//
//                $map['create_time'] = time();
//                $map['update_time'] = time();
//                $map['remark']      = '开'.$name.'宝箱';
//                $map['class']       = $type;
//
//                $data = $v;
//                $data['nick_name'] = self::staticInfo('nick_name',$this->user_id);
//                $data['user_id']   = hashid($this->user_id);
//                $data['remark']    = $map['remark'];
//                if (is_numeric(input('room_id'))){
////                    $this->sendRoomMsg(input('room_id'),'activity',$data);
//                    //砸中大礼物进行推送
//
//                    if ($v['price'] >= self::getExplain('mini_price')){
//                        $roomInfo = $this->roomInfo(input('room_id'),'room_name,img,type,room_id,is_lock,password,cid');
//                        $title = sprintf('恭喜【%s】刚刚在%s宝箱中获得【%s钻】x%s，又一波奖品已来袭~快来试试手气吧',$data['nick_name'],$name,$v['name'].'/'.$v['price'],$v['num']);
//                       j_push($title,'all',$roomInfo);
//                    }
//
//                }
//
//                Db::name('draw_record')->insert($map);
//            }
//            Db::commit();
//        }catch (Exception $e){
//            Db::rollback();
//            api_return(0,$e->getMessage());
//        }
//        $new = arr_sort($Prizes,'price');
//        api_return(1,'成功打开箱子',$new);
//    }
    public function openBox()
    {

        $this->checkAct();

        $data = input('post.');

        switch ($data['type']){
            case 4://铜宝箱

                $name = '铜';
                break;
            case 5://银宝箱
                $name = '银';
                break;
            case 6://金宝箱
                $name = '金';
                break;
            default:
                api_return(0,'参数错误');
        }

        $type = $data['type'];

        if (!isInt($data['num'])){
            api_return(0,'开启数量错误');
        }

        $max = self::getExplain('openMax')??100;
        if ($data['num'] > $max){
            api_return(0,sprintf("宝箱每次最多只能开%s个哦~",$max));
        }

        $model = new MyPackage();

        if (self::getExplain('boxAct') !== 'true'){
            //宝箱无限模式关闭
            $map['user_id'] = $this->user_id;
            $map['type']    = $data['type'];
            $row   = $model->where($map)->find();

            if (!$row || $row['num'] < $data['num']){
                api_return(0,'宝箱剩余数量不足');
            }
        }

        $price = self::getExplain('box'.$data['type']);
        $total = bcmul($price,$data['num']);

        if ($this->userBalance($this->user_id)['total'] < $total){
            api_return(0,'余额不足');
        }

        $map2['status'] = 1;
        $map2['type']   = 1;

        $rows   = Db::name('draw')->where($map2)->cache(3)->select();
        $proArr = [];
        $prize  = [];

        foreach ($rows as $value){
            $proArr[$value['id']]  = $value['box'.$data['type']];

            $prize[$value['id']]   = $value;
        }

        $win = [];

        $custom['user_id'] = $this->user_id;
        $custom['status']  = 1;
        $custom['type']    = $type;
        $drawCustom = DrawCustom::where($custom)->find();

        for ($i = 1;$i <= $data['num'];$i++){
            $id = DrawService::draw1('box'.$data['type']);

            if ($drawCustom && $i == $data['num']){

                $num = $data['num'] - $drawCustom['num'];

                if ($i > $num){
                    if (!isset($win[$drawCustom['draw_id']]) || $win[$drawCustom['draw_id']] < $drawCustom['num']){
                        $id = $drawCustom['draw_id'];
                    }
                }

//                if (!isset($win[$drawCustom['draw_id']])){
//
//                }
                $drawCustom->save(['status'=>2]);
            }

            if ($id){
                if (isset($win[$id])){
                    $win[$id] ++;
                }else{
                    $win[$id] = 1;
                }
            }

        }

        $Prizes = [];
        //算出中了哪些奖品
        foreach ($win as $k => $v){
            if ($k == 11){ //k等于11即未中奖
                continue;
            }
            $item['key']    = $prize[$k]['key'];
//            $item['user_id'] = $this->user_id;
            $item['type']   = $prize[$k]['type'];
            $item['remark'] = $prize[$k]['remark'];
            $item['num']    = $v;

            if ($item['type'] == 1){
                $item['name']  = getGiftName($item['key']);
                $item['img']   = getGiftImg($item['key']);
                $item['price'] = getGiftPrice($item['key']);
            }else{
                $item['name']  = $prize[$k]['name'];
                $item['img']   = $prize[$k]['img'];
                $item['price'] = $prize[$k]['price'];
            }
            $Prizes[] = $item;
        }

        Db::startTrans();
        try{

            if (self::getExplain('boxAct') !== 'true'){
                // 2019-7-23 宝箱非无限模式扣除背包
                //更新宝箱
                $row->setDec('num',$data['num']);
            }

            //扣钱
            $this->moneyDec($total,$this->user_id);
            money_detail(2,$this->user_id,'抽奖活动->购买'.$data['num'].'把'.$name.'钥匙',$total);

//            $insert  = [];
//            $insert2 = [];
//            $update  = [];

            //更新背包及中奖记录
            foreach ($Prizes as $k => $v){
                $map = [];
                $map['user_id'] = $this->user_id;
                $map['type']    = $v['type'];
                $map['key']     = $v['key'];
                $has = $model->where($map)->find();
                if ($has){
//                    $map['num'] = $has['num']+$v['num'];
                    $model->where('p_id',$has['p_id'])->setInc('num',$v['num']);
//                    $update[] = $map;
                }else{
                    $map['num'] = $v['num'];
//                    $insert[] = $map;
                    $model->insert($map);
                }

                $map['num']   = $v['num'];
                $map['total'] = $v['price'] * $v['num'];
                $map['price'] = $v['price'];

                $map['create_time'] = time();
                $map['update_time'] = time();
                $map['remark']      = '开'.$name.'宝箱';
                $map['class']       = $type;

                $data = $v;
                $data['nick_name'] = self::staticInfo('nick_name',$this->user_id);
                $data['level'] = AppService::getUserInfo('level',$this->user_id);
                $data['user_id']   = hashid($this->user_id);
                $data['remark']    = $map['remark'];

                $push[] = $data;
//                $insert2[] = $map;

                Db::name('draw_record')->insert($map);
            }
//            if (!empty($update)) $model->saveAll($update);
//            if (!empty($insert)) $model->insertAll($insert);
//            if (!empty($insert2)) DrawRecord::insertAll($insert2);

            Db::commit();
        }catch (Exception $e){
            Db::rollback();

            $cache = cache('openBoxLog');
            $error['msg'] = 'openBoxLogRecord';
            $error['request']['param'] = \request()->param();
            $error['request']['header'] = \request()->header();
            $error['e'] = json_encode($e);
            $cache[] = $error;
            cache('openBoxLog',$cache);
            Log::write(json_encode($error),'xiaosong');

            api_return(0,$e->getMessage());
        }


        foreach ($push as $k => $data){

            if (is_numeric(input('room_id'))){
                if ($data['price'] >= self::getExplain('activity_mini')){
                    $this->sendRoomMsg('all','activity',$data);
                }
                //砸中大礼物进行推送

                if ($data['price'] >= self::getExplain('mini_price')){
                    $roomInfo = $this->roomInfo(input('room_id'),'room_name,img,type,room_id,is_lock,password,cid');
                    $title = sprintf('恭喜【%s】刚刚在%s宝箱中获得【%s钻】x%s，又一波奖品已来袭~快来试试手气吧',$data['nick_name'],$name,$data['name'].'/'.$data['price'],$data['num']);
                    j_push($title,'all',$roomInfo);
                }

            }
        }

        $new = arr_sort($Prizes,'price');
        api_return(1,'成功打开箱子',$new);
    }

    /**
     * 获取我的宝箱数量及最高价值物品
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function getBox()
    {

        for ($i = 4 ;$i <= 6;$i++){
            $map['user_id'] = $this->user_id;
            $map['type']    = $i;
            $rows['box'.$i]['num'] = Db::name('my_package')->where($map)->value('num')??0;
            $draw = [];
            $draw['box'.$i] = ['neq',0];
            $draw['status'] = 1;
            $gift = Db::name('draw')->where($draw)->order('price desc')->field('name,type,img,key,price')->find();
            if ($gift['type'] == 1){
                $gift['name'] = getGiftName($gift['key']);
                $gift['img']  = getGiftImg($gift['key']);
            }
            $rows['box'.$i]['gift'] = $gift;
        }
        $where['a.class'] = ['between',[2,4]];

        $lastInfo = Db::name('draw_record')
            ->alias('a')
            ->order('a.record_id desc')
            ->join('users u','u.user_id = a.user_id','left')
            ->field('a.type,a.key,a.create_time,u.nick_name,u.header_img,a.num')
            ->find();
        if ($lastInfo['type'] == 1){
            $lastInfo['name'] = getGiftName($lastInfo['key']);
            $lastInfo['img']  = getGiftImg($lastInfo['key']);
        }else{
            $lastInfo['name'] = Db::name('draw')->where('id',$lastInfo['key'])->cache(3)->value('name');
            $lastInfo['img']  = Db::name('draw')->where('id',$lastInfo['key'])->cache(3)->value('img');
        }
        $lastInfo['create_time'] = formatTime($lastInfo['create_time']);
        $rows['lastInfo'] = $lastInfo;

        api_return(1,'获取成功',$rows);

    }



}